package com.hex.tcpproxy.hx;

import com.hex.tcpproxy.process.FakeServer;
import com.hex.tcpproxy.util.ProxyHandler;
import com.hex.tcpproxy.util.ProxyServer;
import netscape.javascript.JSObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MasterServer implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(MasterServer.class);
    private Integer port;
    private ProxyHandler proxyHandler;
    private Map<String, SalveServer> salveServerMap = new ConcurrentHashMap<>();

    public MasterServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        proxyHandler = new ProxyHandler() {
            @Override
            public void read(String address, byte[] bytes) {
                DataPacket dataPacket = new DataPacket(bytes);
                if ("0.0.0.0:0".equals(dataPacket.getOrigin())) {
                    logger.info("客户端反馈{}", new String(dataPacket.getRealData()));
                } else {
                    SalveServer salveServer = salveServerMap.get(dataPacket.getTarget());
                    if (salveServer != null) {
                        System.out.println(dataPacket.getOrigin());
                        salveServer.write(dataPacket.getOrigin(), dataPacket.getRealData());
                    } else {
                        logger.info("未找到{},{} Server", dataPacket.getOrigin(), dataPacket.getTarget());
                    }

                }
            }
        };
        ProxyServer server = new ProxyServer(port, proxyHandler);
        server.bind();
    }

    public void openSlave(int port, String address) {
        SalveServer salveServer = new SalveServer(port, address, this);
        salveServerMap.put(address, salveServer);
        Thread thread = new Thread(salveServer);
        try {
            thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void write(String origin, String target, byte[] bytes) {
        DataPacket dataPacket = new DataPacket(origin, target, bytes);
        proxyHandler.writeAll(dataPacket.getAllData());
    }


}
